﻿using System.Collections.ObjectModel;
using System.Data.Entity.Validation;
using PortalWeb.Core.Entity;
using Microsoft.AspNet.Identity.EntityFramework;
using PortalWeb.Dao.Base;

namespace PortalWeb.Dao.Migrations
{
    using System;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<ApplicationIdentityDbContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(ApplicationIdentityDbContext context)
        {
            try
            {
                SeedDemoUser(context);
                SeedDemoRoleGroup(context);
                SeedDemoRole(context);
                SeedDemoUsersRoles(context);
                SeedDemoFunction(context);
                SeedDemoFunctionsRoles(context);
            }
            catch (DbEntityValidationException ex)
            {
                string error = string.Empty;
                foreach (var errorItem in ex.EntityValidationErrors)
                {
                    foreach (var errorstring in errorItem.ValidationErrors)
                    {
                        error += errorstring.ErrorMessage;
                    }
                }
                throw new Exception(error);
            }
        }


        private const string EMAIL_ADMIN = "admin@admin.com";
        private const string EMAIL_NORMAL_USER = "normal@admin.com";
        private const string EMAIL_MOD = "mod@admin.com";

        private void SeedDemoUser(ApplicationIdentityDbContext context)
        {
            var adminUser = new ApplicationUser
            {
                Id = Guid.NewGuid().ToString(),
                UserName = EMAIL_ADMIN,
                Email = EMAIL_ADMIN,
                NickName = "系统管理员",
                SecurityStamp = Guid.NewGuid().ToString()
            };
            var normalLUser = new ApplicationUser
            {
                Id = Guid.NewGuid().ToString(),
                UserName = EMAIL_NORMAL_USER,
                Email = EMAIL_NORMAL_USER,
                NickName = "用户1",
                SecurityStamp = Guid.NewGuid().ToString()
            };
            var modUser = new ApplicationUser
            {
                Id = Guid.NewGuid().ToString(),
                UserName = EMAIL_MOD,
                Email = EMAIL_MOD,
                NickName = "用户2",
                SecurityStamp = Guid.NewGuid().ToString()
            };
            context.Set<ApplicationUser>().AddOrUpdate(p => p.Email, adminUser);
            context.Set<ApplicationUser>().AddOrUpdate(p => p.Email, normalLUser);
            context.Set<ApplicationUser>().AddOrUpdate(p => p.Email, modUser);

            context.SaveChanges();
        }

        private void SeedDemoRoleGroup(ApplicationIdentityDbContext context)
        {
            context.Set<RoleGroup>().AddOrUpdate(p => p.Name, new RoleGroup
            {
                Name = "根",
            });
            context.SaveChanges();
            var roleGroup = context.Set<RoleGroup>().Single(d => d.Name == "根");
            context.Set<RoleGroup>().AddOrUpdate(p => p.Name, new RoleGroup
            {
                ParentId = roleGroup.Id,
                Name = "第一分公司",
            });
            context.Set<RoleGroup>().AddOrUpdate(p => p.Name, new RoleGroup
            {
                ParentId = roleGroup.Id,
                Name = "第二分公司",
            });
            context.SaveChanges();
        }

        private void SeedDemoRole(ApplicationIdentityDbContext context)
        {
            var roleGroup = context.Set<RoleGroup>().Single(d => d.Name == "根");
            context.Set<ApplicationRole>().AddOrUpdate(p => p.Name, new ApplicationRole
            {
                Id = Guid.NewGuid().ToString(),
                GroupId = roleGroup.Id,
                Name = RoleConst.ADMINISTRATOR,
                Describe = "管理员角色"
            });
            context.Set<ApplicationRole>().AddOrUpdate(p => p.Name, new ApplicationRole
            {
                Id = Guid.NewGuid().ToString(),
                GroupId = roleGroup.Id,
                Name = RoleConst.NORMAL_USER,
                Describe = "普通用户角色"
            });
            context.Set<ApplicationRole>().AddOrUpdate(p => p.Name, new ApplicationRole
            {
                Id = Guid.NewGuid().ToString(),
                GroupId = roleGroup.Id,
                Name = RoleConst.MODERATOR,
                Describe = "主持人角色"
            });
            context.SaveChanges();
        }

        private void SeedDemoUsersRoles(ApplicationIdentityDbContext context)
        {
            var administratorRole = context.Set<ApplicationRole>().Single(d => d.Name == RoleConst.ADMINISTRATOR);
            var normalRole = context.Set<ApplicationRole>().Single(d => d.Name == RoleConst.NORMAL_USER);
            var moderatorRole = context.Set<ApplicationRole>().Single(d => d.Name == RoleConst.MODERATOR);

            var administratorUser = context.Set<ApplicationUser>().Single(d => d.Email == EMAIL_ADMIN);
            var normalUser = context.Set<ApplicationUser>().Single(d => d.Email == EMAIL_NORMAL_USER);
            var modUser = context.Set<ApplicationUser>().Single(d => d.Email == EMAIL_MOD);

            context.Set<IdentityUserRole>().AddOrUpdate(new IdentityUserRole
            {
                UserId = administratorUser.Id,
                RoleId = administratorRole.Id
            });
            context.Set<IdentityUserRole>().AddOrUpdate(new IdentityUserRole
            {
                UserId = normalUser.Id,
                RoleId = administratorRole.Id
            });
            context.Set<IdentityUserRole>().AddOrUpdate(new IdentityUserRole
            {
                UserId = normalUser.Id,
                RoleId = moderatorRole.Id
            });
            context.Set<IdentityUserRole>().AddOrUpdate(new IdentityUserRole
            {
                UserId = modUser.Id,
                RoleId = normalRole.Id
            });

            context.SaveChanges();
        }

        private void SeedDemoFunction(ApplicationIdentityDbContext context)
        {
            var user = context.Set<ApplicationUser>().Single(d => d.UserName == EMAIL_ADMIN);
            context.Set<Function>().AddOrUpdate(p => p.Name, new Function
            {
                Name = "系统管理",
                Icon= "fa fa-desktop",
                ActionUrl = "/Admin/Home/Index",
                OperationTime = DateTime.Now,
                Operator = user.Id,
            });
            context.SaveChanges();
            var systemFunction = context.Set<Function>().Single(d => d.Name == "系统管理");
            context.Set<Function>().AddOrUpdate(p => p.Name, new Function
            {
                ParentId = systemFunction.Id,
                Name = "用户管理",
                ActionUrl = "/Admin/User/Index",
                OperationTime = DateTime.Now,
                Operator = user.Id,
            });
            context.Set<Function>().AddOrUpdate(p => p.Name, new Function
            {
                ParentId = systemFunction.Id,
                Name = "角色管理",
                ActionUrl = "/Admin/Role/Index",
                OperationTime = DateTime.Now,
                Operator = user.Id,
            });
            context.Set<Function>().AddOrUpdate(p => p.Name, new Function
            {
                ParentId = systemFunction.Id,
                Name = "功能入口",
                ActionUrl = "/Admin/Function/Index",
                OperationTime = DateTime.Now,
                Operator = user.Id,
            });
            context.Set<Function>().AddOrUpdate(p => p.Name, new Function
            {
                ParentId = systemFunction.Id,
                Name = "权限管理",
                ActionUrl = "/Admin/Authorize/Index",
                OperationTime = DateTime.Now,
                Operator = user.Id,
            });
            context.SaveChanges();

            context.Set<Function>().AddOrUpdate(p => p.Name, new Function
            {
                Name = "CMS管理",
                Icon = "fa fa-file-text",
                ActionUrl = "/Cms/Admin/Category/Index",
                OperationTime = DateTime.Now,
                Operator = user.Id,
            });
            context.SaveChanges();
            var cmsFunction = context.Set<Function>().Single(d => d.Name == "CMS管理");
            context.Set<Function>().AddOrUpdate(p => p.Name, new Function
            {
                ParentId = cmsFunction.Id,
                Name = "栏目管理",
                ActionUrl = "/CmsAdmin/Category/Index",
                OperationTime = DateTime.Now,
                Operator = user.Id,
            });
            context.Set<Function>().AddOrUpdate(p => p.Name, new Function
            {
                ParentId = cmsFunction.Id,
                Name = "文章管理",
                ActionUrl = "/CmsAdmin/Article/Index",
                OperationTime = DateTime.Now,
                Operator = user.Id,
            });
            context.SaveChanges();
        }

        private void SeedDemoFunctionsRoles(ApplicationIdentityDbContext context)
        {
            var systemFunction = context.Set<Function>().Single(d => d.Name == "系统管理");
            var administratorRole = context.Set<ApplicationRole>().Single(d => d.Name == RoleConst.ADMINISTRATOR);
            if (administratorRole.Functions == null)
            {
                administratorRole.Functions = new Collection<Function>();
            }
            administratorRole.Functions.Add(systemFunction);
            context.SaveChanges();
        }
    }
}
